package com.wm.yigongfang.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wm.yigongfang.common.config.ServiceException;
import com.wm.yigongfang.dto.res.WeixinRes;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.rmi.ServerException;

/**
 * @Author ZhangPeng
 * @Date 2024/3/8 11:54
 * @PackageName:com.wm.yigongfang.utils
 * @ClassName: WXUtil
 * @Description: TODO
 */

public class WXUtil {

    private static final String APP_ID = "wx3973eb8f168a2c8c";
    private static final String SECRET = "813866ff9368a08af15e58eac8380ec5";
    private static final String GRANT_TYPE = "authorization_code";

    /**
     * 发送请求到微信服务器以获取session信息
     *
     * @param jsCode 登录时获取的code
     * @return 服务器响应的内容
     */
    public static WeixinRes getSessionInfo(String jsCode) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        requestUrl += "?appid=" + APP_ID;
        requestUrl += "&secret=" + SECRET;
        requestUrl += "&js_code=" + jsCode;
        requestUrl += "&grant_type=" + GRANT_TYPE;

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 连接
            connection.connect();

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 使用Hutool工具解析JSON
            WeixinRes weixinRes = JSONUtil.toBean(JSONUtil.parseObj(response.toString()), WeixinRes.class);

            if (weixinRes.getErrmsg() != null) {
                throw new ServerException(weixinRes.getErrmsg());
            }

            // 确保openid有值
            if (weixinRes.getOpenid().isEmpty() || weixinRes.getSession_key().isEmpty()) {
                throw new ServerException("Error: openid or session_key is empty.");
            }
            // 返回响应内容
            return weixinRes;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }
}
